// https://www.jianshu.com/p/10feab2c3102/
// https://blog.csdn.net/zgrbsbf/article/details/81585567

// http://www.voidcn.com/article/p-uovzcrdo-bqu.html
// 动态创建组件

import { ThisReceiver } from '@angular/compiler';
import { ViewCompileResult } from '@angular/compiler/src/view_compiler/view_compiler';
import { Component, OnInit, ComponentFactoryResolver,ViewContainerRef,ViewChild, ComponentFactory } from '@angular/core';
import { FormBuilder, Validators, FormArray} from '@angular/forms';
import { MsgComponent} from '../msg/msg.component'

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.css']
})
export class ReactiveFormsComponent implements OnInit {

  @ViewChild('dynamicCon', {read:ViewContainerRef}) dynamicCon;

  constructor(
    private fb:FormBuilder,
    private resolver: ComponentFactoryResolver
  ) { }

  ngOnInit(): void {
  }


  ngAfterViewInit() {
    console.log(this.dynamicCon.injector)
  }


  formbuilder = {
    type:'',
    key:'',
    value:''
  }

  dynamicCmp;

  addComponent() {
    const factory:ComponentFactory<MsgComponent> = this.resolver.resolveComponentFactory(MsgComponent);
    this.dynamicCmp = this.dynamicCon.createComponent(factory);
  }



  objectKeys = Object.keys;

  profileForm = this.fb.group({
    firstname:['',Validators.required],
    data:this.fb.array([])
  })


  updateForm() {
    console.log('update form');
    this.profileForm.patchValue({
      fistname:'hello world.',
      data:this.fb.array([])
    })
  }


  get form() {
    return this.profileForm.getRawValue() as FormArray;
  }
  get data1() {
    // return this.profileForm.getRawValue() as FormArray
    return this.profileForm.get('data') as FormArray
  }

  addFormItem() {
    this.profileForm.addControl(this.formbuilder.key, this.fb.control(this.formbuilder.value))

  }
  test1() {
    console.log('clcik to add a item')
    // let data = this.profileForm.get('data') as FormArray;
    // data.push(this.fb.control('aa'));
    // this.profileForm.get('data').push(this.fb.control('aa'))
    console.log(this.data1)
    // this.data1.push(this.fb.control("aa"))
    this.profileForm.addControl('aa',this.fb.control('hello worl.d'))
  }
  test() {
  }
  addFormItems() {
    

  }


  onSubmit() {
    console.log('submit');
    console.log(this.profileForm.value)
  }

}
